<?php

class GearmanJobServerCLIController extends DooCliController {
	
	//
	// Usage: php cli.php stop_job_servers
	//
	function stop_job_servers(){
	
		//find current local job servers 
		foreach(Doo::db()->find('GearmanJobServers', array('where' => 'local = 1')) as $js){
			//stop job_server
			$p = new Process();
			if(isset($js->pid)){
				$p->setPid($js->pid);
				$p->stop();
			}
			$js->pid = null;
			$js->update(array('setnulls' => true));
		}
	}
	
	//
	// Usage: php cli.php check_job_servers 
	//
	function check_job_servers(){

		//loop schemas
		foreach(Doo::db()->find('Schemata') as $s){

			$schema_id = $s->id;

			//enabled config with PID
			foreach(Doo::db()->find('GearmanJobServers', array('where' => 'local = 1 AND enabled = 1 AND pid IS NOT NULL AND schema_id = ' . $schema_id)) as $js){

				//init
				$p = new Process();
				$p->setPid($js->pid);
			
				//check status
				if(!$p->status()){

					//let start
					$js->pid = $this->start_local_job_server($js->port);
					$js->update();	
				}	
			}

			//enabled config with missing
			foreach(Doo::db()->find('GearmanJobServers', array('where' => 'local = 1 AND enabled = 1 AND pid IS NULL AND schema_id = ' . $schema_id)) as $js){
				//let start
				$js->pid = $this->start_local_job_server($js->port);
				$js->update();	
			}

			//disabled config
			foreach(Doo::db()->find('GearmanJobServers', array('where' => 'local = 1 AND enabled = 0 AND pid IS NOT NULL AND schema_id = ' . $schema_id)) as $js){
				//stop
				$p = new Process();
				$p->setPid($js->pid);
				$p->stop();
				$js->pid = null;
				$js->update(array('setnulls' => true));
				
			}
		}
	}
	
	function start_local_job_server($port){
		//send command to shell
		$cmd = "/usr/sbin/gearmand -L 127.0.0.1 -p $port -P /tmp/gearmand_{$port}_pid -v  > " . Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . "log/gearmand.log 2>&1 &";
		$p = new Process($cmd);

		//wait for pid to get written
		sleep(1);

		//return pid
		return file_get_contents("/tmp/gearmand_{$port}_pid");
	}
}
